/**
 * @Author : woon
 * @Timestamp : 2016-06-29
 */

var page = sm("do_Page");
var app = sm("do_App");
var nf = sm("do_Notification");
var hashdata = mm("do_HashData");

var circleUrl = require("url/circle");
var httpSilence = require("helper/httpSilence");
var circleHelper = require("helper/circle");
var noData = [{"template":2}];
//声明UI变量
var listview=ui("listView");
var listdata = mm("do_ListData");
listview.bindItems(listdata);//绑定item的数据

var circleCache = sm("do_DataCache");
var chchekey4circleList = "cache_qq_my_manage_circles";

//本页面-ajax业务请求url
var httpUrl = circleUrl.url.base.myManageCircles;

//订阅“退出圈子”事件
page.on("quit_circle", function() {
	binddata();
	app.fire("fire_reflash_circle_count");
});

//从新增页面返回,刷新数据
page.on("result", function(data){
    if (data.circle_delete || data.circle_reflesh) {
    	binddata();
    	app.fire("fire_reflash_circle_count");
    }
});


//当页面加载完毕后执行
page.on("loaded", function() {
	//deviceone.print("myJoinCircle.ui --- page...loaded");
	binddata();
});

//订阅 “点击【我管理的圈子】”页签
page.on("myManageCircle_tab_touch", function(index) {
	binddata();
});

//全部刷新数据
function binddata(){
	if(circleCache.hasData(chchekey4circleList)){
		var circleListInCache = circleCache.loadData({key:chchekey4circleList});
		listdata.removeAll();//清除数据
		listdata.addData(circleListInCache);
		listview.refreshItems();//刷新item数据
	}
	
	httpSilence.post(httpUrl,{},function(data){
		var circleList = data.circleList;
		listdata.removeAll();//清除数据
		if(circleList.length){
			for(var i=0;i<circleList.length;i++){
				if(circleList[i].isOfficial==false){
					circleList[i].template=0;
					circleList[i].rightTemplate=1;
				}
			}
			listdata.addData(circleList);
			listview.refreshItems();//刷新item数据
			circleCache.saveData({key:chchekey4circleList, value:circleList});//缓存到本地
		}else{
			listdata.addData(noData);
			listview.refreshItems();//刷新item数据
		}
	});
}

//下拉列表，刷新数据
listview.on("pull", function(data){
	if (data.state == 2){
		binddata();
		listview.rebound();//复位【一定要做】
	}
});

//上拉列表，翻页数据
listview.on("push", function(data){
	if (data.state == 2){
		binddata();
		listview.rebound();//复位【一定要做】
	}
});

//点击一个圈子
listview.on("touch", function(data){
	var onCircle = listdata.getOne(data);
	var circleId = onCircle.id;
	var circleName = onCircle.name;
	circleHelper.toCircleDetail(circleId,circleName);
});